package com.ajieee.merge.runner.finance;

import com.ajieee.merge.entity.finance.po.StockQuotePO;
import com.ajieee.merge.enums.finance.EtlType;
import com.ajieee.merge.enums.finance.Exchange;
import com.ajieee.merge.mapper.StockQuoteMapper;
import com.ajieee.merge.util.DateUtils;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.client.RestClient;
import org.springframework.web.util.UriComponentsBuilder;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ajieee
 * @date 2025-10-13
 */
@Order(EtlOrder.QUOTE_ORDER)
@Component
@RequiredArgsConstructor
public class SseStockQuoteEtl extends AbstractEtl {

	private final RestClient restClient;

	private final StockQuoteMapper stockQuoteMapper;

	@Override
	public void doExecute() {
		String uriString = UriComponentsBuilder.fromUriString("https://yunhq.sse.com.cn:32042/v1/sh1/list/exchange/equity")
				.queryParam("select", "code,name,open,high,low,last,volume,amount,change,chg_rate")
				.queryParam("begin", 0)
				.queryParam("end", -1)
				.build().encode().toUriString();
		JsonNode rootNode = restClient.get()
				.uri(uriString)
				.header("Referer", "https://www.sse.com.cn/")
				.retrieve()
				.body(JsonNode.class);
		Assert.notNull(rootNode, "上证股票行情获取失败");

		JsonNode data = rootNode.get("list");
		LocalDate date = DateUtils.parseDate(rootNode.get("date").asInt(), "yyyyMMdd");
		List<StockQuotePO> pos = new ArrayList<>(data.size());
		for (JsonNode node : data) {
			StockQuotePO po = new StockQuotePO();
			po.setDataDate(date);
			po.setStockCode(node.get(0).asText());
			po.setOpen(node.get(2).asDouble());
			po.setHigh(node.get(3).asDouble());
			po.setLow(node.get(4).asDouble());
			po.setClose(node.get(5).asDouble());
			po.setVolume(node.get(6).asDouble());
			po.setAmount(node.get(7).asDouble());
			po.setChange(node.get(8).asDouble());
			po.setChangeRatio(node.get(9).asDouble());

			pos.add(po);
		}

		if (!pos.isEmpty()) {
			stockQuoteMapper.deleteByDataDateAndExchange(date, Exchange.SSE);
			stockQuoteMapper.insert(pos);
		}
	}

	@Override
	public EtlType getType() {
		return EtlType.SSE_STOCK_QUOTE;
	}
}
